package cl.solidit.geomanagement.web.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import cl.solidit.geomanagement.persistance.UserDAO;
import cl.solidit.geomanagement.persistance.model.Usuario;

@Controller
public class LoginController {
	@Autowired
	private UserDAO userDAO;
	@Transactional
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public ModelAndView login(@RequestParam String usuario,
			@RequestParam String password,HttpServletRequest request) {
		Usuario u=userDAO.login(usuario, password);
		if (u!=null) {
			request.getSession().setAttribute("username", u.getNombre());
			request.getSession().setAttribute("rol", u.getRol().getId());
			request.getSession().setAttribute("rut", u.getPersona().getRut());
			request.getSession().setAttribute("userId", u.getId());
			return new ModelAndView("index");
		} else {
			return new ModelAndView("login","error","Nombre de usuario o password invalidos.");
			
		}

	}
	@RequestMapping(value = "/", method = RequestMethod.GET)
	public ModelAndView index() {
		return new ModelAndView("index");

	}
	
	@RequestMapping(value = "/index_gerente", method = RequestMethod.GET)
	public ModelAndView indexGerente() {
		return new ModelAndView("index_gerente");

	}
	
	@RequestMapping(value = "/index_agente", method = RequestMethod.GET)
	public ModelAndView indexAgente() {
		return new ModelAndView("index_agente");

	}

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public ModelAndView loginForm(HttpServletRequest request) {
		if(request.getSession().getAttribute("username")!=null)
			return index();
		return new ModelAndView("login");

	}
	@RequestMapping(value = "/logout", method = RequestMethod.GET)
	public ModelAndView Logout(HttpServletRequest request) {
		
		request.getSession().setAttribute("username", null);
		request.getSession().setAttribute("rol", null);
		request.getSession().setAttribute("rut", null);
		return new ModelAndView("login");
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");

	}

}
